import { checkType, randomNum } from "../sharde/utils";

const reg_onClick = /onClick\=\"(.+?)\"/g;
const reg_fnName = /^(.+?)\(/;
const reg_arg = /\((.*?)\)/

/**
 * eventPool = []
 * {
 *    mark: 当前DOM
 *    handler：事件处理函数的字符串
 *    type: 事件类型
 * }
 */

const eventPool = [];

export function eventFormat(template) {
  return template.replace(reg_onClick, function (node, key) {
    const _mark = randomNum();

    eventPool.push({
      mark: _mark,
      handler: key.trim(),
      type: 'click'
    })

    return `data-mark="${_mark}"`;
  })
}

export function bindEvent(methods) {
  const allElement = document.querySelectorAll('*');
  let oItem = null,
    _mark = 0;

  eventPool.forEach(event => {
    for (let i = 0; i < allElement.length; i++) {
      oItem = allElement[i];
      _mark = parseInt(oItem.dataset.mark)

      if (event.mark === _mark) {
        oItem.addEventListener(event.type, function () {
          const fnName = event.handler.match(reg_fnName)[1]
          //TODO: arg 限制为number string boolean
          const arg = checkType(event.handler.match(reg_arg)[1]);

          methods[fnName](arg);
          console.log(fnName, arg)
        }, false)
      }
    }
  })
}